import {
    showMsg
  } from "../../utils/config";
  import {
    validateMobile
  } from "../../utils/validate"
import {
    reqBindMobile,
    reqSmsCode,
    reqCheckCode
  } from '../../request/api.js';

  var app = getApp()
  Page({
    data: {
      navHeight: app.globalData.navHeight + 'px', //头部距离
      phone: '',
      showCountDown: false,
    },
    onLoad(options) {
      this.setData({
        phone: options.phone,
        type: options.type
      })
      this.getSmsCodeClick()
    },
    clearCode() {
      this.setData({
        code: ''
      })
    },
    inputCode(e) {
      this.setData({
        code: e.detail
      })
    },
    /**
     * @name: 点击获取短信
     * @msg:  mobile
     * @return {*} smsCode
     */
    async getSmsCodeClick() {
      if (this.data.showCountDown) return
      let {
        phone
      } = this.data
      if (!validateMobile(phone)) return
      const res = await reqSmsCode({
        mobile: phone,
      })
      if (res.code != 20000) return showMsg(res.message);
      showMsg("请注意查收手机短信验证码")
      this.setData({
        showCountDown: true,
        countDown: 180,
        smsCodeMobile: phone
      })
      this.data.intervalId && clearInterval(this.data.intervalId)
      this.setData({
        intervalId: setInterval(() => {
          let {
            countDown
          } = this.data
          if (this.data.countDown > 0 && this.data.countDown <= 180) {
            countDown -= 1
            this.setData({
              countDown
            })
          } else {
            this.setData({
              showCountDown: false
            })
            clearInterval(this.data.intervalId);
          }
        }, 1000)
      })
    },
    onUnload() {
      this.data.intervalId && clearInterval(this.data.intervalId)
      this.setData({
        intervalId: this.data.intervalId
      })
    },
    onNextPage() {
      if (!this.data.phone) return showMsg('请输入手机号')
      if (this.data.type == 1) {
        this.onCheckCode()
      } else {
        this.onBindNewPhone()
      }
    },
  
    // 校验手机号
    async onCheckCode() {
      let res = await reqCheckCode({
        mobile: this.data.phone,
        code: this.data.code
      })
      if (res.code != 20000) return showMsg(res.message);
      if(res.data.result == true) {
        wx.navigateTo({
          url: `/pages/setNewPhone/setNewPhone`,
        })
      } else {
        showMsg('验证码输入错误')
      }
    },
    // 绑定
    async onBindNewPhone() {
      let res = await reqBindMobile({
        mobile: this.data.phone,
        id: app.globalData.userId
      })
      if (res.code != 20000) return showMsg(res.message);
      app.globalData.mobile = this.data.phone
      wx.setStorageSync('mobile', this.data.phone)
      wx.navigateTo({
        url: `/pages/successNewPhone/successNewPhone`,
      })
    }
  })